import React, { useRef, useState } from 'react'
import { SearchOutlined } from '@ant-design/icons'
import type { GetRef, TableColumnsType, TableColumnType } from 'antd'
import { Button, Input, Space, Table } from 'antd'
import type { FilterDropdownProps } from 'antd/es/table/interface'
import Highlighter from 'react-highlight-words'
import './index.css'
type InputRef = GetRef<typeof Input>

interface VTableProps {
  width?: number
  bordered?: boolean
  columns: any
  data: any
}
const VTable: React.FC<VTableProps> = ({ columns, data }) => {
  const [searchText, setSearchText] = useState('')
  const [searchedColumn, setSearchedColumn] = useState('')
  const searchInput = useRef<InputRef>(null)

  const handleSearch = (selectedKeys: string[], confirm: FilterDropdownProps['confirm'], dataIndex: string) => {
    confirm()
    setSearchText(selectedKeys[0])
    setSearchedColumn(dataIndex)
  }

  const handleReset = (clearFilters: () => void,dataIndex:string) => {
    clearFilters()
    setSearchText('')
    setSearchedColumn(dataIndex)
  
  }

  const getColumnSearchProps = (dataIndex: string): TableColumnType<any> => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, close }) => (
      <div  style={{ padding: 8 }} onKeyDown={e => e.stopPropagation()}>
        <Input ref={searchInput} placeholder={`请输入`} value={selectedKeys[0]} onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])} onPressEnter={() => handleSearch(selectedKeys as string[], confirm, dataIndex)} style={{ marginBottom: 8, display: 'block' }} />
        <Space>
          <Button type="primary" onClick={() => handleSearch(selectedKeys as string[], confirm, dataIndex)} icon={<SearchOutlined />} size="small" style={{ width: 90 }}>
            搜索
          </Button>
          <Button onClick={() => clearFilters && handleReset(clearFilters,dataIndex)} size="small" style={{ width: 90 }}>
            重置
          </Button>

          <Button
            type="link"
            size="small"
            onClick={() => {
              close()
            }}>
            关闭
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered: boolean) => <SearchOutlined style={{ color: filtered ? '#1677ff' : undefined }} />,
    onFilter: (value, record) =>
      record[dataIndex]
        .toString()
        .toLowerCase()
        .includes((value as string).toLowerCase()),
    onFilterDropdownOpenChange: visible => {
      if (visible) {
        setTimeout(() => (searchInput.current! as HTMLInputElement).select(), 100)
      }
    },
    render: text => (searchedColumn === dataIndex ? <Highlighter highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }} searchWords={[searchText]} autoEscape textToHighlight={text ? text.toString() : ''} /> : text)
  })

  return (
 
    <Table
      columns={columns.map((item: any) => {
        if (item.search) {
          return {
            ...item,
            /** 设置表头可搜索 */
            ...getColumnSearchProps(`${item.dataIndex}`)
          }
        } else {
          return item
        }
      })}
      dataSource={data.map((item: any, index: number) => {return {...item,key:index}} )}
      /** 分页设置 */
      pagination={{defaultCurrent:1, pageSize:5,total: data.length, showTotal: (total, range) => `共 ${total} 条`}}
      rowKey={"key"}
    />
  )
}

export default VTable
